'use strict';
var jwt = require('jsonwebtoken');
const Controller = require('egg').Controller;

class LoginController extends Controller {
  async index() {
    const { name, password } = this.ctx.request.body;
    // const user = {
    //   id: '0001',
    //   name: 'admin',
    //   password: '123456'
    // }

    // if (user.name === name && user.password === password) {
    const user = await this.ctx.model.User.findOne({ name, password })
    if (user) {
      this.ctx.session.userId = user._id;
      this.ctx.session.userName = user.name;
      const token = jwt.sign({ id: user._id, name }, 'aaa', { expiresIn: '1d' });
      this.ctx.cookies.set('token', token, {
        maxAge: 1000*3600*24,
        httpOnly: false, // 默认就是 true
        encrypt: true, // 加密传输
      });
      this.ctx.body = {
          code: 1,
          msg: '登录成功',
          userId: user.id
      };
    }
    else {
      this.ctx.body = {
          code: -1,
          msg: '用户名或密码错误'
      };
    }
  }

  async register() {
    const { username, password, email, phone } = this.ctx.request.body;
    if (username && password && email && phone) {
      this.ctx.body = {
        code: 1,
        msg: '注册成功（模拟注册，并不会创建真实账户哦～）'
      }
    }
    else {
      this.ctx.body = {
        code: -90002,
        msg: '注册失败'
      } 
    }
  }

  async appRegister() {
    const { name, password } = this.ctx.request.body;
    const user = await this.ctx.model.User.findOne({ name })
    if (user) {
      this.ctx.body = {
        code: -90002,
        msg: "用户已存在"
      };
    } else {
      try {
        const res = await this.ctx.model.User.create({
          name,
          password
        });
        this.ctx.body = {
          code: 1,
          msg: "注册成功"
        };
      } catch (err) {
        this.ctx.body = {
          code: -1,
          msg: err
        };
      }
    }
  }

  async getUser() {
    this.ctx.body = {
        userId: '0001',
        userName: 'admin'
    };
  }

  async appGetUser() {
    const token = this.ctx.cookies.get("token", {
      signed: false,
      encrypt: true
    });
    const decoded = jwt.verify(token, "aaa");
    const res = await this.ctx.model.User.findOne({ _id: decoded.id });
    console.log('=======', res.name)
    this.ctx.body = {
      code: 1,
      msg: 'ok',
      data: {
        userId: res._id,
        name: res.name
      }
    };
  }

  async logout() {
    this.ctx.session = null;
    this.ctx.cookies.set('token', '');
    this.ctx.body = {
        code: 1,
        msg: '登出成功'
    };
  }

  async redirect() {
    this.ctx.body = {
        code: -90001,
        msg: '未登录'
    };
  }
}

module.exports = LoginController;
